import requests  # pip install requests
import json
import base64
import hashlib
import hmac
import time #for nonce

class BitfinexClient(object):
    BASE_URL = "https://api.bitfinex.com/"
    KEY=""
    SECRET=""

    def __init__(self, apikey, secretkey):
        self.KEY = apikey
        self.SECRET = secretkey

    def _nonce(self):
        """
        Returns a nonce
        Used in authentication
        """
        return str(int(round(time.time() * 1000)))

    def _headers(self, body):

        payload = base64.b64encode(body.encode(encoding='utf-8'))
        h = hmac.new(self.SECRET.encode(encoding='utf-8'), payload, hashlib.sha384)
        signature = h.hexdigest()

        return {
            "X-BFX-APIKEY": self.KEY,
            "X-BFX-PAYLOAD": payload,
            "X-BFX-SIGNATURE": signature
        }

    def account_infos(self):
        """
        Fetch active orders
        """
        path = "/v1/balances"
        nonce = self._nonce()
        body = {'request': path,'nonce' : nonce}
        rawBody = json.dumps(body)



        #print(self.BASE_URL + path)
        #print(nonce)


        headers = self._headers(rawBody)



        #print("requests.post("+self.BASE_URL + path + ", headers=" + str(headers) + ", data=" + rawBody + ", verify=True)")
        r = requests.post(self.BASE_URL + path, headers=headers, data=rawBody, verify=True)

        if r.status_code == 200:
          return r.json()
        else:
          print(r.status_code)
          print(r.content)
          return ''
